
<template>
  <div>
    <el-form
      :model="dataForm"
      :rules="formRules"
      ref="dataForm"
      label-width="80px"
    >
      <el-form-item prop="GID" label="可见机构">
        <el-cascader
          v-model="dataForm.GID"
          :options="organizeMix"
          :props="{
            multiple: false,
            value: 'GID',
            label: 'name',
            children: 'children',
            checkStrictly: true,
            emitPath: false,
          }"
          :show-all-levels="false"
          clearable
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="投票标题" prop="title">
        <el-input v-model="dataForm.title" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="截止时间" prop="stopTime">
        <el-date-picker
          :editable="false"
          v-model="dataForm.stopTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择时间"
          clearable
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="投票描述" prop="text">
        <el-input
          v-model="dataForm.text"
          auto-complete="off"
          type="textarea"
          :rows="4"
        ></el-input>
      </el-form-item>
          <!-- <el-col v-if="answer && answer.length > 0">
          <el-row v-for="(item, index) in answer" :key="index" :gutter="20">
            <el-col :span="4">
              <el-input
                placeholder="选项名"
                :disabled="!(currentAID == index)"
                v-model="item.name"
                auto-complete="off"
              ></el-input>
            </el-col>
            <el-col :span="12">
              <el-input
                placeholder="选项内容"
                :disabled="!(currentAID == index)"
                v-model="item.text"
                auto-complete="off"
              ></el-input>
            </el-col>
            <el-col v-if="currentAID == index" :span="2">
              <el-button
                @click="addOtherAnswer(item)"
                type="success"
                icon="el-icon-check"
                circle
              ></el-button>
            </el-col>
            <el-col v-else :span="2">
              <el-button
                @click="changeFocus(index)"
                type="warning"
                icon="el-icon-edit"
                circle
              ></el-button>
            </el-col>
            <el-col :span="2">
              <el-button
                @click="deleteOne(item, index)"
                type="danger"
                icon="el-icon-minus"
                circle
              ></el-button>
            </el-col>
            <el-col
              v-if="index == answer.length - 1 && currentAID !== index"
              :span="2"
            >
              <el-button
                @click="addOne"
                type="primary"
                icon="el-icon-plus"
                circle
              ></el-button>
            </el-col>
          </el-row>
        </el-col>
        <el-row v-else>
          <el-col :span="4">
            <el-input
              placeholder="选项名"
              v-model="firstName"
              auto-complete="off"
            ></el-input>
          </el-col>
          <el-col :offset="1" :span="12">
            <el-input
              placeholder="选项内容"
              v-model="firstAnswer"
              auto-complete="off"
            ></el-input>
          </el-col>
          <el-col :offset="1" :span="3">
            <el-button
              @click="addAnswer(firstAnswer)"
              type="success"
              icon="el-icon-check"
              circle
            ></el-button>
          </el-col>
        </el-row> -->
        
     <!-- </el-form-item> -->
      <el-form-item label="图片" prop="describe">
        <div class="row">
          <el-image
            @click="deleteImg(item, index)"
            v-for="(item, index) in dataForm.imgs"
            :key="index"
            :src="getItemPhoto(item)"
            class="avatar el-upload--picture-card mr20"
          ></el-image>

          <el-upload
            ref="uploadImg"
            :show-file-list="false"
            action="#"
            list-type="picture-card"
            :http-request="handleUpLoad"
            :on-success="handleSuccess"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer cen">
      <el-button @click.native="closedialog">取消</el-button>
      <el-button type="primary" @click.native="submitForm">确定</el-button>
    </div>
  </div>
</template>
<script>
export default {
  props: {
    data: {
      type: Object,
      default: function () {
        return {
          title: "",
          text: "",
          imgs: [],
        };
      },
    },
  },
  data() {
    return {
      dataForm: {
        title: "",
        text: "",
        imgs: [],
        GID: "",
      },
      getCommunity: [],
      answer: [],
      firstAnswer: "",
      firstName: "",
      currentAID: 999,
      formRules: {
        title: [{ required: true, message: "标题必填", trigger: "blur" }],
        GID: [{ required: true, message: "小区必选", trigger: "blur" }],
        text: [{ required: true, message: "内容必填", trigger: "blur" }],
        stopTime: [{ required: true, message: "时间必填", trigger: "blur" }],
      },
    };
  },
  methods: {
   
    // 关闭
    closedialog() {
      this.$emit("handleSave");
    },
    addOne() {
      this.answer.push({
        name: "",
        txt: "",
      });
      this.currentAID = this.answer.length - 1;
    },
    deleteImg(item, index) {
      this.$confirm("确认删除此照片吗？", "提示", {}).then(() => {
        this.dataForm.imgs.splice(index, 1);
      });
    },
    changeFocus(AID) {
      this.currentAID = AID;
    },
    //新增第一条选项
    addAnswer(item) {
      if (this.firstName == "" || this.firstAnswer == "") {
        this.$message({
          message: "请填写完整",
          type: "error",
        });
        return;
      }
      let params = {
        CID: this.dataForm.CID,
        VID: this.dataForm.VID,
        name: this.firstName,
        text: this.firstAnswer,
        status: 1,
      };
      this.$api.wxNotic.weixin_answer_operate({ where: params }).then((res) => {
        //  this.answer = res.data;
        this.getChose(this.dataForm);
      });
    },
    //新增修改其他选项
    addOtherAnswer(item) {
      let params = Object.assign({}, item);
      params.CID = this.dataForm.CID;
      params.VID = this.dataForm.VID;
      params.status = 1;
      this.$api.wxNotic.weixin_answer_operate({ where: params }).then((res) => {
        //this.answer = res.data;
        this.currentAID = 999;
        this.getChose(this.dataForm);
      });
    },
    //删除选项
    deleteOne(item, index) {
      if (!item.AID) {
        this.answer.splice(index, 1);
        return;
      }
      this.$confirm("确认删除当前选项吗？", "提示", {}).then(() => {
        let params = Object.assign({}, item);
        params.GID = this.dataForm.GID;
        params.VID = this.dataForm.VID;
        params.status = 2;
        this.$api.wxNotic
          .weixin_answer_operate({ where: params })
          .then((res) => {
            this.currentAID = 999;
            this.getChose(this.dataForm);
          });
      });
    },
    // 表单提交
    submitForm() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.editLoading = true;
            let params = Object.assign({}, this.dataForm);
            
            this.$api.wxNotic.weixin_vote_add({ where: params }).then((res) => {
              this.editLoading = false;
              if (res.code == 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                });
                this.$emit("handleSave");
                // this.handleClose();
              } else {
                this.$message({
                  message: "操作失败, " + res.msg,
                  type: "error",
                });
              }
              this.findTreeData();
            });
          });
        }
      });
    },
    //获取选项
    getChose(row) {
      let params = {
        CID: row.CID,
        VID: row.VID,
        status: 1,
        sort: { name: 1 },
      };
      this.$api.wxNotic.weixin_answer_list(params).then((res) => {
        this.answer = res.data;
      });
    },
    async handleUpLoad(param) {
      // 编辑添加图片
      var imgup = "";
      await this.getBase64(param.file).then((res) => {
        imgup = res;
      });
      var paramd = {
        img: imgup,
      };
      this.$api.imgAdd.addimgPer(paramd).then((res) => {
        this.dataForm.imgs.push(res.id);
      });
    },
    // 拼接图片
    getItemPhoto(id) {
      var url = this.global.baseUrlImage + "avatar/" + id;
      return url;
    },
    //图片处理
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handleSuccess(res, file) {},
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    getCommunityList() {
      let params = {};
      params = {
        where: {
          CODES: [],
        },
      };
      let param = JSON.stringify(params);
      this.loading = true;
      this.$api.three.communityList(params).then((res) => {
        if (res.code == 0) {
          this.loading = false;
          this.getCommunity = res.data;
          this.getCommunity.unshift({ CID: "7458120", name: "全部" });
        } else {
          this.$message({ message: "操作失败, " + res.msg, type: "error" });
        }
      });
    },
  },
  async mounted() {
    this.dataForm = this.data;
    this.dataForm.stopTime = new Date(this.dataForm.stopTime);

    this.getChose(this.dataForm);
    this.organizeMix = await this.getOrganizeMix();
    console.log(this.organizeMix)
  },
};
</script>

<style lang="scss" scoped>
.cen {
  text-align: center;
}
.row {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
.mr20 {
  margin-right: 20px;
}
.myselect {
  width: 100%;
}
.el-select {
  width: 100%;
}
</style>
